package com.biz.limit.aspect;

import com.biz.limit.annotation.ApiLimit;
import com.biz.limit.enums.LimitType;
import com.biz.limit.exection.BusinessException;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * @author LXY
 * @Description
 * @create 2024/09/24
 */
@Aspect
@Configuration
@Slf4j
public class LimitInterceptorAspect {
    private final RedisTemplate<String, Serializable> limitRedisTemplate;

    public LimitInterceptorAspect(RedisTemplate redisTemplate, RedisTemplate<String, Serializable> limitRedisTemplate) {
        this.limitRedisTemplate = limitRedisTemplate;
    }

    @Around("execution(public * *(..)) && @annotation(com.biz.limit.annotation.ApiLimit)")
    public Object interceptor(ProceedingJoinPoint joinPoint){
        //获取连接点的方法签名对象
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //获取方法实例
        Method method = methodSignature.getMethod();
        //获取注解实例
        ApiLimit limitAnnotation = method.getAnnotation(ApiLimit.class);
        //注解中的类型
        LimitType limitType = limitAnnotation.limitType();
        //获取key名称
        String name = limitAnnotation.name();
        String key;
        //获取限制时间范围
        int limitPeriod = limitAnnotation.period();
        //获取限制访问次数
        int limitCount = limitAnnotation.count();
        switch (limitType){
            //如果类型是IP，则根据IP限制访问次数，key取IP地址
            case IP:
                key = getIPAdress();
                break;
            //如果类型是customer，则根据key限制访问次数
            case CUSTOMER:
                key = limitAnnotation.key();
                break;
            //否则按照方法名称限制访问次数
            default:
                key = StringUtils.upperCase(method.getName());
        }
        ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(),key));
        try{
            String luaScript = buildLuaScript();
            RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
            Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod);
            if(count !=null && count.intValue() <= limitCount){
                return joinPoint.proceed();
            }else{
                throw new BusinessException("访问超限");
            }
        }catch(Throwable e){
            log.error("异常：{}", e.getMessage(), e);
            if(e instanceof RuntimeException){
                throw new RuntimeException(e.getLocalizedMessage());
            }
            throw new RuntimeException("服务异常");
        }
    }

    /**
     * lua限流脚本
     * @return
     */
    public String buildLuaScript(){
        StringBuilder sb = new StringBuilder();
        //定义c
        sb.append("local c");
        //获取redis中的值
        sb.append("\nc = redis.call('get',KEYS[1])");
        //如果调用不超过最大值
        sb.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then");
        //直接返回
        sb.append("\n return c;");
        //结束
        sb.append("\nend");
        //访问次数加一
        sb.append("\nc = redis.call('incr',KEYS[1])");
        //如果是第一次调用
        sb.append("\nif tonumber(c) == 1 then");
        //设置对应值的过期设置
        sb.append("\nredis.call('expire',KEYS[1],ARGV[2])");
        //结束
        sb.append("\nend");
        //返回
        sb.append("\nreturn c;");

        return sb.toString();
    }

    private static final String UNKONW = "unknown";

    /**
     * 获取访问IP
     * @return
     */
    public String getIPAdress(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getHeader("x-forword-for");
        if(ip == null || ip.length() ==0 || UNKONW.equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Clent-IP");
        }
        if(ip == null || ip.length() ==0 || UNKONW.equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Clent-IP");
        }
        if(ip == null || ip.length() ==0 || UNKONW.equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
